<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('Alohacart')) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) www.volter.org (welcome@volter.org)
 * @link       http://code.google.com/p/aloha-cart-v2/
 */

/**
 *  Class that represents shopping Cart
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
class Alohacart {
    /**
     * Session variable for the Cart
     * Data is stored in format: id_article=>quantity
     */
    private $_session_data;
    
    /**
     *  EcataloguE ProductModel
     */
    private $product_mdl;
	
	/**
	 *  EcataloguE CurrencyModel
	 */
	private $currency_mdl;
    
    public function __construct() {        
        // We'll use standart PHP session. But in future we can change it to SPIP session        
        @session_start();
        //$_SESSION["alohacart"] = array();
        if (!isset($_SESSION["alohacart"]) || !is_array($_SESSION["alohacart"])) {
      		$_SESSION["alohacart"] = array();
    	}
        $this->_session_data = &$_SESSION["alohacart"];
        
        $this->product_mdl = pdk_load_class('ProductModel','classes');
		$this->currency_mdl = pdk_load_class('CurrencyModel','classes');
    }
    
    /**
     *  Get array of products IDs that are located in the Cart 
     */
    public function GetProductsIDs() {
        $ids = array();
        foreach($this->_session_data as $key=>$value){
			$ids[] = $value[0];
        }
        return $ids;
    }
    
    /**
     *  Get array of products (quantities actually) that are located in the Cart 
     */
    public function GetProducts() {
		//print_r($_SESSION);
        return $this->_session_data;
    }
    
    /**
     *  Gets products total prices array in format: array(id_article1=>total_price1, id_article2=>total_price2)
	 *  in current currency 
     */
    public function GetProductsTotals() {
        $totals = array();
        $products = $this->GetProducts();
        foreach ($products as $array=>$value) {
            $price = $this->product_mdl->GetProductPrice($value[0], $this->currency_mdl->GetCurrentCurrencyCode());
            $price2 = $price*$value[1];
                if(strstr($price2,'.')!==FALSE) {
                    $price2 = number_format($price2,2,'.','');
                }
                $totals[] = $price2;
        }
        return $totals;
    }


    
    /**
     *  Remove all products from the Cart
     */
    public function ClearCart() {
		$this->_session_data = array();
  	}
    
    /**
     *  Count all products in the Cart
     *  @return Number of products in the Cart
     */

    public function CountProducts() {
        $cart_num = count($this->_session_data);
        if(strstr($cart_num,'.')!==FALSE) {
            $cart_num = number_format($cart_num,2,'.','');
        }
        return $cart_num;
    }

    
    /**
     *  Count total price of products in the Cart in current currency
     *  NB: Price will be calculated according to product's currency rate
	 *	
	 *  !!!! ecatalogue_product !!!! get price from  ecatalogue_product 
	 *
     *  @return Price of all products in the Cart
     */
    
    public function CountPrice($currency = false) {
        $cart_price = 0;
        foreach ($this->_session_data as $array=>$value) {
            $product_price = $this->product_mdl->GetProductPrice($value[0], 'UAH');
            $cart_num = 0;
	    	$cart_num += $value[1];
            $cart_price += $product_price*$value[1];
        }
        if(strstr($cart_price,'.')!==FALSE) {
            $cart_price = number_format($cart_price,2,'.','');
        }
        return $cart_price;
    }

    /**
     *  Count total price of products in the Cart in current currency
     *  NB: Price will be calculated according to product's currency rate
	 *	
	 *  !!!! ecatalogue_prices !!!! get price from  ecatalogue_prices 
	 *
     *  @return Price of all products in the Cart
     */
    
    public function CartRetailPrice($currency = false) {
        $cart_price = 0;
        foreach ($this->_session_data as $array=>$value) {
            $product_price = $this->product_mdl->GetRetailPrice($value[0]);
            $cart_num = 0;
	    	$cart_num += $value[1];
            $cart_price += $product_price*$value[1];
        }
        if(strstr($cart_price,'.')!==FALSE) {
            $cart_price = number_format($cart_price,2,'.','');
        }
        return intval(round($cart_price));
    }

    /**
     *  Count total number of items in cart
     *  
	 *
     *  @return Number of items (not sku!) in cart
     */


	public function CountItems() {
        $quantity = 0;
        foreach ($this->_session_data as $array=>$value) {
	    	$quantity += $value[1];
        }

		return $quantity;
	}



    /**
     *  Add product to cart
     */
	public function AddProduct($id_article, $quantity = 1, $options = array()) {
		// Если корзина пуста, просто добавляем новый товар
		if (!isset($this->_session_data[0]) && !isset($this->_session_data[1])) {
			$this->_session_data[1] = array($id_article, $quantity, $options);
		} else {
		// Если в корзине есть товар - сравниваем новый товар со всеми, которые есть в корзине
			$check = false;
			$i = 0;
			foreach ($this->_session_data as $array=>$value) {
				// сравнивание товара по его ID
				// если товар с таким ID уже существует - проверяем его опции, не существует - добавляем новый товар в корзину
				if (($value[0] == $id_article) && (!$check) && !($check_id)) {
					$check_position = $array;
					$check_id = true;
					if (isset($value[2]) && is_array($value[2]))
					{
						$options_array = $value[2];
						foreach ($options as $option_name=>$option_value) {
							// Проверка на наличие ключа ("размер:"\"цвет:")
							if (array_key_exists($option_name, $options_array)) {
								// Если ключ имееться - проверяем его значение
								if ($option_value == $options_array[$option_name]) {
									$check = true;
									$check_data_0 = $value[0];
									$check_data_1 = $value[1];
									$check_data_2 = $value[2];
								}
							} else {
								$check = false;
							}
						}
					} else $check = false;
				}
			}
			if ($check) {
				$this->_session_data[$check_position][1] += $quantity;
			} else if ($check_id) {
				$this->_session_data[$check_position][1] += $quantity;
			} else {
				$this->_session_data[] = array($id_article, $quantity, $options);
			}
		}
	}
    /**
     *  Remove product from the Cart
     *  @param int $quantity How much products to remove
     */
    public function RemoveProduct($id_article, $quantity=false) {
		if ($product_index = $this->GetProductIndexInSessionData($id_article)) {
			unset($this->_session_data[$product_index]);
		}
		//if ($id_article==0 || empty($id_article) || !isset ($id_article)) {
			//array_shift($this->_session_data);
		//} else {
			//unset($this->_session_data[$id_article]);
		//}
		ksort($this->_session_data);
		/* OLD
        $id_article = explode('_',$id_article);
        $sub_id_article = (isset($id_article[1]))?$id_article[1]:false;
        $id_article = $id_article[0];
        if (!$quantity)
            if($sub_id_article!==false){
                unset($this->_session_data[$id_article][$sub_id_article]);
                sort($this->_session_data[$id_article]);
            }
            else if (isset($this->_session_data[$id_article])) {
                if (isset($this->_session_data[$id_article][$sub_id_article])) {
                    $this->_session_data[$id_article][$sub_id_article][0] -= $quantity;
                    if ($this->_session_data[$id_article][$sub_id_article][0] <= 0){
                        unset($this->_session_data[$id_article][$sub_id_article]);
                        sort($this->_session_data[$id_article]);
                    }
                }
            }
		*/
    }

    /**
     *  Update product in the cart
     */
    public function Updateproduct($id_article, $quantity) {
		if ($product_index = $this->GetProductIndexInSessionData($id_article)) {			
			$this->_session_data[$product_index][1] = $quantity;
		}
			
    }
	
	/**
	 *	Сохранение в сессии данных о валюте, которую выбрал для себя пользователь
	 */
	public function Save_currency_by ($currency = 'uah'){
		$_SESSION['currency_choice'] = $currency;
	}
	/**
	 *	Возвращает выбранную пользователем валюту
	 */
	public function Get_currency_by (){
		$currency_by = &$_SESSION["currency_choice"];
		return $currency_by;
	}
	
	private function GetProductIndexInSessionData($id_article)
	{
		foreach ($this->_session_data as $key=>$product)
		{
			if ($product[0] == $id_article)
				return $key;
		}
		return false;
	}
} 
?>